package com.jrh.web.admin;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jrh.biz.brand.BrandService;
import com.jrh.biz.product.set.ProductSetService;
import com.jrh.domain.entity.Brand;
import com.jrh.domain.entity.ProductSet;
import com.jrh.domain.user.LoginUserInfo;
import com.jrh.web.member.tools.UserAuthUtil;

/**
 * 产品系列
 * 
 * @author yout 2012-7-27 下午10:11:03
 */
@Controller
@RequestMapping("/seller/productSet/")
public class AdminProductSetController {

    @Autowired
    private ProductSetService productSetService;

    @Autowired
    private BrandService      brandService;

    @RequestMapping(value = "/list")
    public String list(Model model, HttpServletRequest request, HttpServletResponse response) {
        LoginUserInfo user = UserAuthUtil.getUserInfo(request, response);
        if (user == null) {
            user = new LoginUserInfo();
            user.setId(1L);
        }
        Brand brand = brandService.getBrandByUserId(user.getUserId());

        if (brand == null) {
            return "/admin/error";
        }

        List<ProductSet> list = productSetService.listSetsByBrandId(brand.getId());
        model.addAttribute("list", list);
        return "/admin/productSet/list";
    }

    @RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
    public String updateView(String success, @PathVariable("id") long id, Model model) {
        ProductSet productSet = productSetService.getProductSetById(id);
        model.addAttribute("data", productSet);
        model.addAttribute("success", Boolean.valueOf(success));
        return "admin/productSet/update";
    }

    @RequestMapping(method = RequestMethod.POST, value = "/update")
    public String update(ProductSet productSet, Model model) {
        productSetService.updateSet(productSet);
        return "redirect:/seller/productSet/update/" + productSet.getId() + ".htm?success=true";
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/delete/{id}")
    public String delete(@PathVariable("id") long id) {
        try {
            productSetService.deleteSet(id);
            return Boolean.TRUE.toString();
        } catch (Exception e) {
            return Boolean.FALSE.toString();
        }
    }

    @RequestMapping("/add")
    public String add(ProductSet productSet) {
        productSet.setBrandId(3);
        productSetService.addSet(productSet);
        return "redirect:/seller/productSet/list.htm";
    }

}
